import api from '../config.js'
import store from '@/store'
const BASE_URL = api.BASE_URL
import {
	saveLog
} from '@/common/utils/index'

export const request = (option) => {
	let timestamp = Date.now()
	const header = {
		// 'Authorization': `Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjA0N2Q2Y2JiLThmZTYtNGNiNy1hOWQyLTJhY2Q1YzU5ZWNkYyJ9.sZEcQAPYRAFZm26BNsgZ4mutnrpKtvuszAEus_tkoNlUYeYOkvvmsWwenS28tE2eGXOcTx33oMSemu6vnqClEQ`,
		// 'x-refresh-token': `Bearer ${uni.getStorageSync('refreshToken')}`,
		'accept-language': 'zh-CN,zh;q=0.9',
		'Content-Type': 'application/json',
		// 'userId': store.state.user.userId || '',
	}

	if (uni.getStorageSync('token')) {
		header.Authorization = `Bearer ${uni.getStorageSync('token')}`
		// header.Authorization = `Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjA0N2Q2Y2JiLThmZTYtNGNiNy1hOWQyLTJhY2Q1YzU5ZWNkYyJ9.sZEcQAPYRAFZm26BNsgZ4mutnrpKtvuszAEus_tkoNlUYeYOkvvmsWwenS28tE2eGXOcTx33oMSemu6vnqClEQ`


	}

	if (!option.isCloseLoading) {
		uni.showLoading({
			mask: true,
			title: ''
		})
	}

	// if (!option?.data?.isCloseLoading) {
	// 	uni.showLoading({
	// 		mask: true,
	// 		title: ''
	// 	})
	// }

	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + option.url,
			method: option.method || 'GET',
			data: option.data || {},
			header: option.header || header,
			timeout: 6000,
			success: (res) => {
				uni.hideLoading()
				switch (res.data.code) {
					case 200:
						resolve(res.data)
						break
					case 401:
						// uni.removeStorageSync('token');
						// uni.removeStorageSync('userInfo');
						uni.clearStorageSync()
						return uni.showToast({
							title: '未登录,请先登录',
							duration: 2500,
							icon: "none",
							success() {
								setTimeout(() => {
									uni.hideToast();
									// uni.switchTab({
									// 	url: '/pages/my/index'
									// })
									uni.navigateTo({
										url: '/pages/login/login'
									})
								}, 1300)
							}
						});
						break
					case 403:
						return uni.showModal({
							title: '提示',
							content: '暂无权限',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									reject('err')
								}
							}
						})
						// reject()
						break
					case 601:
						reject('err')
						// reject()
						break
					default:
						// console.log('option', option)
						console.log('res', res)
						// saveLog('requset', option)
						// saveLog('requset', res.data)
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: res.data.msg || '服务器错误',
							duration: 3000,
							mask: true,
							success: (res) => {
								reject('err')
							}
						})
						break
				}
			},
			fail: (err) => {
				uni.hideLoading()
				console.log('接口错误', err);
				// saveLog('requset', err)
				uni.showToast({
					title: '服务器错误',
					icon: 'error'
				})
				reject(err)
			}
		})
	})
}